package com.yingdong.gateserver.net;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yingdong.gateserver.innter.message.GameMessage;
import com.yingdong.gateserver.opcode.Dispatcher;
import com.yingdong.gateserver.opcode.InternalOpcode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class GateClientHandlerNetty4 extends ChannelInboundHandlerAdapter {
	static Log logger = LogFactory.getLog(GateClientHandlerNetty4.class);

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Dispatcher.sceneServerSession = ctx.channel();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		for (GameSession gameSession : Dispatcher.sessionMap.values()) {
			gameSession.getChannel().close();
		}
		logger.info("连接中断");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buffer = (ByteBuf) msg;
		try {
			// Dispatcher.sendBuffers.put(buffer);

			int allength = buffer.readInt();
			int length = buffer.readInt();
			int opcode = buffer.readInt();
			buffer.readerIndex(length);
			ByteBuf buffer2 = null;
			while (buffer.isReadable()) {
				int session = buffer.readInt();
				if (session == 0) {
					for (GameSession gamesession : Dispatcher.sessionMap.values()) {
						buffer2 = buffer.slice(4, length);
						gamesession.getChannel().writeAndFlush(buffer2);
						buffer.retain();
					}
					break;
				}
				buffer2 = buffer.slice(4, length);
				GameSession gamesession = Dispatcher.sessionMap.get(session);
				if (gamesession != null) {
					Channel sessionChannel = Dispatcher.sessionMap.get(session).getChannel();
					if (opcode == InternalOpcode.ALREADY_LOGIN) {
						Dispatcher.reconnectedMap.put(session, session);
						sessionChannel.writeAndFlush(buffer2);
						buffer.retain();
					} else {
						if (Dispatcher.handlerTable1[opcode] != null) {
							GameMessage message = new GameMessage(opcode, session, buffer2);
							Dispatcher.handlerTable1[opcode].handle(session, message);

						} else {
							sessionChannel.writeAndFlush(buffer2);
							buffer.retain();
						}
					}

				}
			}
			buffer.release();
		} catch (Exception e1) {

			logger.debug("", e1);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// logger.info("", cause);
	}

}
